//
//  XJCycleView.m
//  CycleScrollView
//
//  Created by lanou3g on 16/4/19.
//  Copyright © 2016年 ZhangXJ. All rights reserved.
//

#import "XJCycleView.h"


typedef void(^TapBlock)(NSInteger index);

@interface XJCycleView () <UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *imgScrollView;
@property (strong, nonatomic) UIPageControl *imgPageControll;
@property (strong, nonatomic) NSMutableArray *imgViewArray;
//存放图片的数组
@property (strong, nonatomic) NSMutableArray *imgArray;

//存储当前图片的索引值
@property (assign, nonatomic) NSInteger index;
//定时器
@property (strong, nonatomic) NSTimer *imgTimer;
@property (assign, nonatomic) NSTimeInterval interval;


//点击回调block
@property (copy, nonatomic) TapBlock tapBlok;
@end


@implementation XJCycleView


//初始化
- (instancetype)initWithFrame:(CGRect)frame andInterVal:(NSTimeInterval)interval {
    
    self.interval = interval;
    
    if (self = [super initWithFrame:frame]) {
        
        self.imgViewArray = [NSMutableArray new];
        self.imgArray = [NSMutableArray new];
       
        self.imgScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.imgScrollView.pagingEnabled = YES;
        self.imgScrollView.showsHorizontalScrollIndicator = NO;
        self.imgScrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height);
        [self addSubview:self.imgScrollView];
        
        self.imgScrollView.delegate = self;
        
        for (int i = 0; i < 3; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(frame.size.width * i, 0, frame.size.width, frame.size.height)];
            
            //添加到视图
            [self.imgScrollView  addSubview:imageView];
            [self.imgViewArray addObject:imageView];
        }
    }

    return self;
}

#pragma mark - 定时器 图片滚动
- (void)timerAction {
    [self.imgScrollView setContentOffset:CGPointMake(self.imgScrollView.frame.size.width * 2, 0) animated:YES];
    
    //改变index
    self.index = (self.index + 1) % self.imgNameArray.count;
}

//图片名数组
- (void)setImgNameArray:(NSMutableArray *)imgNameArray {
    if (_imgNameArray != imgNameArray) {
        _imgNameArray = imgNameArray;
        
        //设置pageControl
        [self.imgPageControll removeFromSuperview];
        self.imgPageControll = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 40, self.frame.size.width, 40)];
        [self addSubview:self.imgPageControll];
        
        //pagecontrol的属性
        self.imgPageControll.currentPage = 0;
        self.imgPageControll.numberOfPages = self.imgNameArray.count;
        self.imgPageControll.enabled = NO;
        self.imgPageControll.pageIndicatorTintColor = [UIColor cyanColor];
        
        for (int i =  0; i < imgNameArray.count; i++) {
            
            UIImage *img = [UIImage imageNamed:imgNameArray[i]];//注意缓存较大时[[NSBundle mainBundle] pathForResource:<#(nullable NSString *)#> ofType:<#(nullable NSString *)#>]
            [self.imgArray addObject:img];
        }
        //循环结束 设置当前偏移量
        [self.imgScrollView setContentOffset:CGPointMake(self.frame.size.width, 0)];
//        self.index = 0;
        [self layOutImages];
        
        
        //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCycleViewAction:)];
    [self.imgViewArray[1] addGestureRecognizer:tap];
    [self.imgViewArray[1] setUserInteractionEnabled:YES];
    }
    
    
    //初始化timer
    if (self.interval <= 0) {
        self.imgTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }else {
        self.imgTimer = [NSTimer scheduledTimerWithTimeInterval:self.interval target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
}


#pragma mark - UIScrollViewDelegate 的代理方法
static CGFloat x = 0;
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    x = scrollView.contentOffset.x;
    
//    [self.imgTimer invalidate];会将定时器销毁 故将起始时间推迟到未来
    [self.imgTimer setFireDate:[NSDate distantFuture]];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (x > scrollView.contentOffset.x) {
        [self panToLeft:NO withIndex:self.index];
    }else if(x < scrollView.contentOffset.x) {
        [self panToLeft:YES withIndex:self.index];
    }
    
    //计时器开始
//    [self.imgTimer setFireDate:[NSDate date]];//立刻开始
    [self.imgTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:2]];//两秒后开始
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    //回位 到中间位置
    [self.imgScrollView setContentOffset:CGPointMake(scrollView.frame.size.width, 0)];
    
    [self layOutImages];//滚动结束切换图片
}

#pragma mark - 向左滑动 向右滑动结束切换图片
- (void)panToLeft:(BOOL)left withIndex:(NSInteger)index {
    
    if (left) {
        self.index = (index + 1) % self.imgNameArray.count;
    }else {
          self.index = (index - 1 + self.imgNameArray.count) % self.imgNameArray.count;
    }
    
    [self layOutImages];

    //回位操作 使偏移位置复原
    [self.imgScrollView setContentOffset:CGPointMake(self.frame.size.width, 0)];
}


- (void)layOutImages {
    for (int i = 0; i < 3; i++) {
        [self.imgViewArray[i] setImage:self.imgArray[(self.index - 1 + self.imgNameArray.count + i) % self.imgNameArray.count]];
    }
}

#pragma mark - self.imgPageControl原点设置
- (void)setIndex:(NSInteger)index {
    if (_index != index) {
        _index = index;
        self.imgPageControll.currentPage = index;
    }
}

#pragma mark - 添加Block回调 -- 获得点击图片的索引
- (void)addTapBlock:(void(^)(NSInteger index))block {
    self.tapBlok = block;
}


- (void)tapCycleViewAction:(UITapGestureRecognizer *)tap {
    if (self.tapBlok) {
        self.tapBlok(self.index);
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
